package com.ahearttogo.rpc.client;

import com.aharttogo.rpc.transport.TransportClient;
import com.ahearttogo.rpc.codec.Decoder;
import com.ahearttogo.rpc.codec.Encoder;
import com.ahearttogo.rpc.common.utils.ReflectionUtil;

import java.lang.reflect.Proxy;
import java.nio.channels.Selector;

/**
 * @author xiejialin
 * @date 2020/2/17 6:57 PM
 */
public class RpcClient {

    private RpcClientConfig clientConfig;

    private Encoder encoder;

    private Decoder decoder;

    private TransportSelector selector;


    public RpcClient() {
        this(new RpcClientConfig());
    }

    public RpcClient(RpcClientConfig clientConfig) {
        this.clientConfig = clientConfig;
        this.encoder = ReflectionUtil.newInstance(clientConfig.getEncoderClass());
        this.decoder = ReflectionUtil.newInstance(clientConfig.getDecoderClass());
        this.selector = ReflectionUtil.newInstance(clientConfig.getSelectorClass());

        this.selector.init(
                this.clientConfig.getServers(),
                this.clientConfig.getConnectCount(),
                this.clientConfig.getTransportClass()
        );
    }

    public <T> T getProxy(Class<T> clazz ){
        //动态代理
        return (T) Proxy.newProxyInstance(
                getClass().getClassLoader(),
                new Class[]{clazz},
                new RemoteInvoker(clazz,encoder,decoder,selector));
    }
}
